package ar.uade.edu.fain.ad.server.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.classic.Session;

import ar.uade.edu.fain.ad.common.transfer.NotaDevolucionVO;
import ar.uade.edu.fain.ad.server.business.NotaDevolucion;
import ar.uade.edu.fain.ad.server.dao.entity.NotaDevolucionEntity;
import ar.uade.edu.fain.ad.server.util.persistence.HibernateUtil;

public interface NotaDevolucionDAO extends GenericDAO<NotaDevolucion, Long> {

	public static class Util {

		public static List<NotaDevolucionVO> buscarDevoluciones() {
			Session session = (Session) HibernateUtil.get().getSession();
			List<NotaDevolucionVO> listaVO;
			try {
				session.beginTransaction();
				@SuppressWarnings("unchecked")
				List<NotaDevolucionEntity> listaEntity = session.createQuery(
						"from NotaDevolucionEntity where impreso=false").list();
				actualizoDevoluciones(listaEntity);
				listaVO = new ArrayList<NotaDevolucionVO>();
				for (int i = 0; i < listaEntity.size(); i++) {
					listaVO.add(NotaDevolucion.toVO(listaEntity.get(i)));
				}
				session.getTransaction().commit();
			} catch (HibernateException e) {
				e.printStackTrace();
				throw new RuntimeException(e.getMessage());
			} finally {
				if (session != null && session.isOpen()) {
					session.close();
				}
			}
			return listaVO;
		}

		private static void actualizoDevoluciones(
				List<NotaDevolucionEntity> lista) {

			Session session = (Session) HibernateUtil.get().getSession();

			for (int i = 0; i < lista.size(); i++) {

				String hql = "UPDATE NotaDevolucionEntity set impreso = true "
						+ "WHERE id = :idnota";
				final Query query = session.createQuery(hql);
				query.setParameter("idnota", lista.get(i).getId());
				int result = query.executeUpdate();
				System.out.println("Rows affected: " + result);
			}

		}

	}

}
